package com.mo.axion.handler.receiver.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.mo.axion.common.domain.AnchorInfo;
import com.mo.axion.common.domain.LogParam;
import com.mo.axion.common.domain.RecallTaskInfo;
import com.mo.axion.common.domain.TaskInfo;
import com.mo.axion.common.enums.AnchorState;
import com.mo.axion.handler.handler.HandlerHolder;
import com.mo.axion.handler.pending.Task;
import com.mo.axion.handler.pending.TaskPendingHolder;
import com.mo.axion.handler.receiver.service.ConsumeService;
import com.mo.axion.handler.utils.GroupIdMappingUtils;
import com.mo.axion.support.utils.LogUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author Mo
 * @createTime 2024/2/17 17:02
 * @description 消费消息服务实现类
 */
@Slf4j
@Service
public class ConsumeServiceImpl implements ConsumeService {

    private static final String LOG_BIZ_TYPE = "Receiver#consumer";
    private static final String LOG_BIZ_RECALL_TYPE = "Receiver#recall";

    @Autowired
    private ApplicationContext context;

    @Autowired
    private TaskPendingHolder taskPendingHolder;

    @Autowired
    private HandlerHolder handlerHolder;

    @Autowired
    private LogUtils logUtils;

    /**
     * 从MQ拉取消息进行消费，发送消息
     *
     * @param taskInfoList
     */
    @Override
    public void consume2Send(List<TaskInfo> taskInfoList) {
        String topicGroupId = GroupIdMappingUtils.getGroupIdByTaskInfo(CollUtil.getFirst(taskInfoList.iterator()));
        for (TaskInfo taskInfo : taskInfoList) {
            logUtils.print(
                    LogParam.builder()
                            .bizType(LOG_BIZ_TYPE)
                            .object(taskInfo).build(),
                    AnchorInfo.builder()
                            .bizId(taskInfo.getBizId())
                            .messageId(taskInfo.getMessageId())
                            .idList(taskInfo.getReceiver())
                            .businessId(taskInfo.getBusinessId())
                            .state(AnchorState.RECEIVE.getCode()).build()
            );
            Task task = context.getBean(Task.class).setTaskInfo(taskInfo);
            taskPendingHolder.route(topicGroupId).execute(task);
        }
    }

    /**
     * 从MQ拉取消息消费，业务撤回消息
     * 如果有recallMessageId，则优先撤回recallMessageId
     * 如果没有 recallMessageId，则撤回整个模板的消息
     * TODO
     * @param recallTaskInfo
     */
    @Override
    public void consume2Recall(RecallTaskInfo recallTaskInfo) {
        logUtils.print(
                LogParam.builder()
                        .bizType(LOG_BIZ_RECALL_TYPE)
                        .object(recallTaskInfo).build()
        );
//        handlerHolder.route(recallTaskInfo.getSendChannel()).recall(recallTaskInfo);
    }
}
